document.addEventListener('DOMContentLoaded', () => {
    const SESSION_KEY = 'app_authenticated';

    // --- DOM Elements ---
    const loginScreen = document.getElementById('login-screen');
    const loginForm = document.getElementById('login-form');
    const passwordInput = document.getElementById('password-input');
    const errorMessage = document.getElementById('error-message');
    const appContainer = document.getElementById('app-container');
    const checkinBtn = document.getElementById('checkin-btn');
    const addPastCheckinBtn = document.getElementById('add-past-checkin-btn');
    const calendarGrid = document.getElementById('calendar-grid');
    const calendarTitle = document.getElementById('calendar-title');
    const detailsTitle = document.getElementById('details-title');
    const detailsList = document.getElementById('details-list');
    const formModal = document.getElementById('form-modal');
    const modalTitle = document.getElementById('modal-title');
    const checkinForm = document.getElementById('checkin-form');
    const recordIdInput = document.getElementById('record-id-input');
    const datetimeInput = document.getElementById('datetime-input');
    const cancelBtn = document.getElementById('cancel-btn');
    const prevMonthBtn = document.getElementById('prev-month-btn');
    const nextMonthBtn = document.getElementById('next-month-btn');
    const statsWeek = document.getElementById('stats-week');
    const statsMonth = document.getElementById('stats-month');
    const statsYear = document.getElementById('stats-year');
    const statsTotal = document.getElementById('stats-total');

    // --- App State ---
    let selectedDate = null;
    let currentDate = new Date();

    // --- Main App Logic ---
    function runApp() {
        loginScreen.classList.add('hidden');
        appContainer.classList.remove('hidden');
        selectedDate = getBeijingTimeISOString().slice(0, 10);
        updateCalendar();
        updateStats();
    }

    // --- API Helper ---
    async function apiRequest(endpoint, method = 'GET', body = null) {
        const options = {
            method,
            headers: { 'Content-Type': 'application/json' },
        };
        if (body) {
            options.body = JSON.stringify(body);
        }
        const response = await fetch(endpoint, options);
        if (!response.ok) {
            const errorResult = await response.json().catch(() => ({ error: 'Request failed' }));
            throw new Error(errorResult.error || 'Request failed');
        }
        return response.json();
    }

    // --- Calendar & Stats Update ---
    async function updateCalendar() {
        const year = currentDate.getFullYear();
        const month = currentDate.getMonth();
        const monthStr = `${year}-${String(month + 1).padStart(2, '0')}`;
        calendarTitle.textContent = `${year}年 ${month + 1}月`;

        try {
            const result = await apiRequest(`/api/data?month=${monthStr}`);
            renderCalendar(result.success ? result.data : {});
            if (selectedDate) {
                updateDetailsSection(selectedDate);
            }
        } catch (error) {
            console.error('Error fetching calendar data:', error);
            renderCalendar({});
        }
    }

    async function updateStats() {
        try {
            const result = await apiRequest('/api/stats');
            if (result.success) {
                statsWeek.textContent = result.stats.thisWeek;
                statsMonth.textContent = result.stats.thisMonth;
                statsYear.textContent = result.stats.thisYear;
                statsTotal.textContent = result.stats.total;
            }
        } catch (error) {
            console.error('Error fetching stats:', error);
        }
    }

    // --- UI Rendering ---
    function renderCalendar(checkinData) {
        calendarGrid.innerHTML = '';
        const year = currentDate.getFullYear();
        const month = currentDate.getMonth();
        const firstDayOfMonth = new Date(year, month, 1).getDay();
        const daysInMonth = new Date(year, month + 1, 0).getDate();
        const today = new Date();

        for (let i = 0; i < firstDayOfMonth; i++) {
            calendarGrid.insertAdjacentHTML('beforeend', '<div></div>');
        }

        for (let i = 1; i <= daysInMonth; i++) {
            const dateStr = `${year}-${String(month + 1).padStart(2, '0')}-${String(i).padStart(2, '0')}`;
            const isToday = (i === today.getDate() && month === today.getMonth() && year === today.getFullYear());
            const count = checkinData[dateStr] || 0;
            
            let dayClasses = 'day cursor-pointer rounded-lg transition-all duration-200';
            if (count > 0) dayClasses += ' bg-green-200 text-green-800 font-bold hover:bg-green-300';
            else dayClasses += ' bg-gray-100 hover:bg-gray-200';
            if (isToday) dayClasses += ' ring-2 ring-indigo-500';
            if (dateStr === selectedDate) dayClasses += ' ring-2 ring-blue-500 scale-110 shadow-md';

            const dayElement = `
                <div class="${dayClasses}" data-date="${dateStr}">
                    <div class="day-number">${i}</div>
                    ${count > 0 ? `<div class="day-count">${count}次</div>` : ''}
                </div>`;
            calendarGrid.insertAdjacentHTML('beforeend', dayElement);
        }
    }

    async function updateDetailsSection(date) {
        selectedDate = date;
        if (!date) {
            detailsTitle.textContent = '点击日期查看详情';
            detailsList.innerHTML = '';
            return;
        }
        detailsTitle.textContent = `${date} 的打卡记录`;
        detailsList.innerHTML = '<li class="text-center text-gray-500">加载中...</li>';
        try {
            const result = await apiRequest(`/api/details?date=${date}`);
            if (result.success && result.records.length > 0) {
                const listHtml = result.records.map(rec => `
                    <li class="flex justify-between items-center py-2 px-3 bg-gray-50 rounded-md shadow-sm">
                        <span>运动于 <span class="font-semibold text-indigo-600">${rec.time}</span>
                        ${rec.remarks ? `<p class="text-gray-600 text-sm mt-1">备注: ${rec.remarks}</p>` : ''}
                        </span>
                        <div class="flex gap-2">
                            <button class="edit-btn text-sm text-blue-600 hover:text-blue-800" data-id="${rec.id}" data-timestamp="${date}T${rec.time}" data-remarks="${rec.remarks || ''}">编辑</button>
                            <button class="delete-btn text-sm text-red-600 hover:text-red-800" data-id="${rec.id}">删除</button>
                        </div>
                    </li>`).join('');
                detailsList.innerHTML = listHtml;
            } else {
                detailsList.innerHTML = '<li class="text-gray-500">当天没有打卡记录。</li>';
            }
        } catch (error) {
            detailsList.innerHTML = `<li class="text-red-500">加载失败: ${error.message}</li>`;
        }
    }

    // Helper to get current Beijing time in YYYY-MM-DDTHH:mm format
    function getBeijingTimeISOString() {
        const now = new Date();
        // Adjust to Beijing time (UTC+8)
        const utc = now.getTime() + (now.getTimezoneOffset() * 60000);
        const beijingTime = new Date(utc + (3600000 * 8));

        const year = beijingTime.getFullYear();
        const month = String(beijingTime.getMonth() + 1).padStart(2, '0');
        const day = String(beijingTime.getDate()).padStart(2, '0');
        const hours = String(beijingTime.getHours()).padStart(2, '0');
        const minutes = String(beijingTime.getMinutes()).padStart(2, '0');

        return `${year}-${month}-${day}T${hours}:${minutes}`;
    }

    // --- Modal Handling ---
    function showModal(isEdit = false, recordId = null, timestamp = '', remarks = '') {
        modalTitle.textContent = isEdit ? '编辑打卡记录' : '补打卡';
        recordIdInput.value = recordId;
        datetimeInput.value = timestamp ? timestamp.slice(0, 16) : getBeijingTimeISOString();
        document.getElementById('modal-remarks-input').value = remarks;
        formModal.classList.remove('hidden');
    }

    function hideModal() {
        formModal.classList.add('hidden');
    }

    // --- Event Listeners ---
    prevMonthBtn.addEventListener('click', () => {
        currentDate.setMonth(currentDate.getMonth() - 1);
        updateCalendar();
    });

    nextMonthBtn.addEventListener('click', () => {
        currentDate.setMonth(currentDate.getMonth() + 1);
        updateCalendar();
    });

    checkinBtn.addEventListener('click', async () => {
        const remarks = document.getElementById('remarks-input').value;
        try {
            await apiRequest('/api/checkin', 'POST', { remarks });
            document.getElementById('remarks-input').value = ''; // Clear remarks after successful check-in
                const now = new Date();
    const beijingTime = new Date(now.valueOf() + 8 * 60 * 60 * 1000);
    const year = beijingTime.getUTCFullYear();
    const month = String(beijingTime.getUTCMonth() + 1).padStart(2, '0');
    const day = String(beijingTime.getUTCDate()).padStart(2, '0');
    const today = `${year}-${month}-${day}`;
            updateCalendar();
            updateStats();
        } catch (error) {
            alert(`打卡失败: ${error.message}`);
        }
    });

    addPastCheckinBtn.addEventListener('click', () => showModal(false));

    calendarGrid.addEventListener('click', (event) => {
        const target = event.target.closest('[data-date]');
        if (target) {
            const date = target.dataset.date;
            updateDetailsSection(date === selectedDate ? null : date);
            updateCalendar(); // Re-render to update selection highlight
        }
    });

    detailsList.addEventListener('click', async (event) => {
        const target = event.target;
        const recordId = target.dataset.id;

        if (target.classList.contains('delete-btn')) {
            if (confirm('确定要删除这条记录吗？')) {
                try {
                    await apiRequest('/api/checkin', 'DELETE', { id: parseInt(recordId) });
                    updateCalendar();
                    updateStats();
                } catch (error) {
                    alert(`删除失败: ${error.message}`);
                }
            }
        } else if (target.classList.contains('edit-btn')) {
            const remarks = target.dataset.remarks;
            showModal(true, recordId, target.dataset.timestamp, remarks);
        }
    });

    checkinForm.addEventListener('submit', async (event) => {
        event.preventDefault();
        const id = recordIdInput.value ? parseInt(recordIdInput.value) : null;
        const localDateTime = datetimeInput.value;
        const modalRemarks = document.getElementById('modal-remarks-input').value;
        const utcTimestamp = new Date(localDateTime).toISOString();

        try {
            if (id) { // Edit
                await apiRequest('/api/checkin', 'PUT', { id: id, new_timestamp: utcTimestamp, remarks: modalRemarks });
            } else { // Add past check-in
                await apiRequest('/api/checkin', 'POST', { timestamp: utcTimestamp, remarks: modalRemarks });
            }
            hideModal();
            selectedDate = localDateTime.slice(0, 10);
            updateCalendar();
            updateStats();
        } catch (error) {
            alert(`操作失败: ${error.message}`);
        }
    });

    cancelBtn.addEventListener('click', hideModal);

    // --- Authentication ---
    if (sessionStorage.getItem(SESSION_KEY) === 'true') {
        runApp();
    } else {
        loginForm.addEventListener('submit', async (event) => {
            event.preventDefault();
            const password = passwordInput.value;
            errorMessage.textContent = '';
            try {
                const result = await apiRequest('/api/login', 'POST', { password });
                if (result.success) {
                    sessionStorage.setItem(SESSION_KEY, 'true');
                    runApp();
                } else {
                    errorMessage.textContent = result.error || '登录失败';
                }
            } catch (error) {
                errorMessage.textContent = `登录请求失败: ${error.message}`;
            }
        });
    }
});
